package hz.mobileproject.pda.ui.activity.work;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.activity.CaptureActivity;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cn.droidlover.xdroidmvp.mvp.XActivity;
import hz.mobileproject.pda.R;
import hz.mobileproject.pda.broadcast.HandleBroadcast;
import hz.mobileproject.pda.broadcast.IShowBarcodeStr;
import hz.mobileproject.pda.entity.request.Request_grid_handle;
import hz.mobileproject.pda.entity.request.Request_loadPersioneInfo;
import hz.mobileproject.pda.entity.request.Request_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_gridPerson_item;
import hz.mobileproject.pda.entity.response.Response_grid_loadtype;
import hz.mobileproject.pda.entity.response.Response_noneProcess_item;
import hz.mobileproject.pda.entity.response.Rp_loadPrisonerInfo;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.presenter.PChoosePeople;
import hz.mobileproject.pda.ui.adapter.GridWangDianMsgAdapter;
import hz.mobileproject.pda.ui.view.LoadingDialog;
import hz.mobileproject.pda.utils.CommonUtil;
import hz.mobileproject.pda.utils.HttpRqUtils;

/**
 * 选择罪犯和事件界面
 */
public class GridChoosePeopleActivity extends XActivity<PChoosePeople> implements IShowBarcodeStr {


    private HandleBroadcast handleBroadcast;
    private SoundPool soundpool;
    private int soundid;
    private boolean on_Off;
    private String policeCode;
    private String persionId;
    private String police_id;
    private String cusnumber;

    private String police_name;
    private String department_id;
    private String department_name;
    private String prisoner_name;


    private TextView tv_policeName;
    private TextView tv_policeID;
    private TextView tv_prisonerID;
    private TextView tv_prisonerName;
    private Gson gson;
    private List<Response_grid_loadtype> mResponse_grid_loadtypeList;
    private TextView tv_talk_pinggu;
    private PopupWindow talkPopwindow;
    private GridWangDianMsgAdapter mWangDianMsgAdapter;
    private Button btn_submit;

    //事件类型
    private String choose_key;

    //提交
    private Response_noneProcess_item mNp_item;
    private String prisoner_id;


    private LoadingDialog mLoadingDialog;


    private static final int REQUEST_CODE_POLICE = 0x1008;
    private static final int REQUEST_CODE_PRISONER = 0x1009;

    private ArrayList<Response_gridPerson_item> gridListPerson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cusnumber = SPUtils.getInstance("app_login").getString("cusnumber");

        mLoadingDialog = new LoadingDialog(this);


        tv_policeName = (TextView) findViewById(R.id.tv_policeName);
        tv_policeID = (TextView) findViewById(R.id.tv_policeID);
        tv_prisonerID = (TextView) findViewById(R.id.tv_prisonerID);
        tv_prisonerName = (TextView) findViewById(R.id.tv_prisonerName);
        tv_talk_pinggu = (TextView) findViewById(R.id.tv_talk_pinggu);
        btn_submit = (Button) findViewById(R.id.btn_submit);
        btn_submit.setOnClickListener(this);

        getP().loadData("",1);
        gson = new Gson();

        mNp_item = (Response_noneProcess_item) getIntent().getSerializableExtra("np_item");
        gridListPerson = (ArrayList<Response_gridPerson_item>) getIntent().getSerializableExtra("grid_person");


        //初始化广播
        initScan(REQUEST_CODE_POLICE);


    }




    @Override
    public void updateText(String msg) {
        LogUtils.e("网格化处理事件界面"+ msg);
        soundpool.play(soundid, 1, 1, 0, 0, 1);

        if (mLoadingDialog.getTag() == REQUEST_CODE_POLICE) {
            //获取民警信息
            getPliceInfoFromSer(msg);
        } else if (mLoadingDialog.getTag() == REQUEST_CODE_PRISONER) {
            //获取罪犯信息
            getPrisonerInfoFromSer(msg);
        }
    }

    private CustomNetCallBack prisonerInfoCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            Rp_loadPrisonerInfo loadPrisonerInfo = new Gson().fromJson(data, Rp_loadPrisonerInfo.class);
            if (loadPrisonerInfo == null) {
                ToastUtils.showLong("罪犯信息为空");
                return;
            }
            prisoner_name=  loadPrisonerInfo.getPrisoner_name();
            //做校验
            boolean flag = false;
            for(int i = 0; i < gridListPerson.size();i++) {
                if(prisoner_name.equals(gridListPerson.get(i).getPrisoner_name())) {
                    flag = true;
                    prisoner_id = loadPrisonerInfo.getPrisoner_id();
                    tv_prisonerName.setText(prisoner_name);
                    tv_prisonerID.setText(persionId);
                    mLoadingDialog.dismiss();
                    break;
                }
            }
            if(!flag) {
                ToastUtils.showLong("扫描的罪犯不在小组名单内");
//                initScan(REQUEST_CODE_PRISONER);
            }



        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取罪犯信息失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取罪犯信息失败");
            LogUtils.e(ex);
        }
    };




    @Override
    public void onWidgetClick(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:  //提交
                if(TextUtils.isEmpty(police_id)) {
                    ToastUtils.showLong("请扫描民警二维码");
                    return;
                }
                if(TextUtils.isEmpty(prisoner_id)) {
                    ToastUtils.showLong("请扫描罪犯二维码");
                    return;
                }
                if(TextUtils.isEmpty(choose_key)) {
                    ToastUtils.showLong("请选择事件");
                    return;
                }
                ToastUtils.showLong("提交");
                Request_grid_handle request_grid_handle = new Request_grid_handle(
                        mNp_item.getCus_number(),
                        mNp_item.getId(),
                        mNp_item.getDept_id(),
                        mNp_item.getDept_name(),
                        mNp_item.getFactory_id(),
                        mNp_item.getFactory_name(),
                        mNp_item.getTerm_id(),
                        mNp_item.getTerm_name(),
                        prisoner_id,
                        prisoner_name,
                        police_id,
                        police_name,
                        TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")),
                        choose_key

                );
                getP().loadData(request_grid_handle,4);
                break;
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {


    }

    /**
     * 打开扫描  兼容摄像头扫描
     * @param requestCode
     */
    private void initScan(int requestCode) {
        if (Constance.isNeiMeng) {  //如果是演示版本则打开相机扫描
            //打开二维码扫描界面
            if (CommonUtil.isCameraCanUse()) {
                Intent intent = new Intent(this, CaptureActivity.class);
                startActivityForResult(intent, requestCode);
            } else {
                Toast.makeText(this, "请打开此应用的摄像头权限！", Toast.LENGTH_SHORT).show();
            }
        } else {
            handleBroadcast = new HandleBroadcast(this, this);
            soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
            soundid = soundpool.load("/etc/Scan_new.ogg", 1);
            if (requestCode == REQUEST_CODE_POLICE) {
                mLoadingDialog.setTag(REQUEST_CODE_POLICE);
                mLoadingDialog.setMessage("请扫描民警二维码").show();
            } else if (requestCode == REQUEST_CODE_PRISONER) {
                mLoadingDialog.setTag(REQUEST_CODE_PRISONER);
                mLoadingDialog.setMessage("请扫描罪犯二维码").show();
            }
        }

    }

    /**
     * 摄像头扫码回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        Bundle bundle = data.getExtras();
        String scanStr = bundle.getString("qr_scan_result");
        if (requestCode == REQUEST_CODE_POLICE) {
            //获取民警信息
            getPliceInfoFromSer(scanStr);
        } else if (requestCode == REQUEST_CODE_PRISONER) {
            //获取罪犯信息
            getPrisonerInfoFromSer(scanStr);
        }
    }

    private void getPliceInfoFromSer(String msg) {
        policeCode = msg.contains("P") ? msg.substring(1): msg;
        Request_loadPoliceInfo loadPoliceInfo = new Request_loadPoliceInfo();
        loadPoliceInfo.setCusNumber(cusnumber);
        loadPoliceInfo.setPoliceCode(policeCode);
        getP().loadData(loadPoliceInfo, 2);   //获取民警信息
    }


    private void getPrisonerInfoFromSer(String msg) {
        persionId=msg;
        //获取罪犯信息
        Request_loadPersioneInfo rq_lpi = new Request_loadPersioneInfo();
        rq_lpi.setCusNumber(SPUtils.getInstance("app_login").getString(Constance.SP_CUSNUMBER));
        rq_lpi.setPrisonerId(msg);
        //发送获取罪犯信息接口请求
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_PRISONER_INFO, rq_lpi, prisonerInfoCallback);
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            handleBroadcast.sendMyBroadcast();

        } catch (Error e) {
            e.printStackTrace();
        }
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_grid_choose_people;
    }

    @Override
    public PChoosePeople newP() {
        return new PChoosePeople();
    }


    public void showData(String s, int type) {
        JSONObject json= null;
        try {
            switch (type) {
                case 1:
                    LogUtils.e(s);
                    mResponse_grid_loadtypeList = gson.fromJson(s,new TypeToken<List<Response_grid_loadtype>>(){}.getType());
                    tv_talk_pinggu.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(talkPopwindow == null) {
                                View msgContentView = createTalkContentView();
                                int width = getWindowManager().getDefaultDisplay().getWidth() * 7 /10;
                                int height = ViewGroup.LayoutParams.WRAP_CONTENT;
                                boolean focusable = true;
                                talkPopwindow = new PopupWindow(msgContentView, width, height, focusable);
                                talkPopwindow.setBackgroundDrawable(new ColorDrawable());  //点击返回键要让popupwindow消失需要给它设置一个背景
                                talkPopwindow.setOutsideTouchable(true);
                            }

                            //显示Popupwindow
                            View anchor = tv_talk_pinggu;   //指定popupWindow显示在什么控件的下方
                            talkPopwindow.showAsDropDown(anchor);

                        }
                    });

                    break;

                case 2://民警信息
                    json = new JSONObject(s);
                    police_name = json.getString("police_name");
                    police_id = json.getString("police_id");
                    department_id = json.getString("department_id");
                    department_name = json.getString("department_name");
                    tv_policeName.setText(police_name);
                    tv_policeID.setText(policeCode);

                    mLoadingDialog.dismiss();
                    initScan(REQUEST_CODE_PRISONER);
                    break;
                case 4:  //上传成功
                    ToastUtils.showLong("上传成功");
                    finish();
                    break;
            }

        }catch (Exception e) {

        }

    }


    private View createTalkContentView() {
        View msgView = View.inflate(this, R.layout.view_qingwuexcute_wangdian_msg_popup,null);
        ListView lv_msg_wangdianqiandao_popup = (ListView) msgView.findViewById(R.id.lv_msg_wangdianqiandao_popup);
        listViewAnimation(lv_msg_wangdianqiandao_popup);
        mWangDianMsgAdapter = new GridWangDianMsgAdapter(mResponse_grid_loadtypeList);
        lv_msg_wangdianqiandao_popup.setAdapter(mWangDianMsgAdapter);
        //点击信息popupWindow条目
        lv_msg_wangdianqiandao_popup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

//                choose_key = mResponse_grid_loadtypeList.get(position).key;
                choose_key = mResponse_grid_loadtypeList.get(position).id;

                for (int i = 0; i < mResponse_grid_loadtypeList.size(); i++) {
                    Response_grid_loadtype response_grid_loadtype = mResponse_grid_loadtypeList.get(i);
                    response_grid_loadtype.isChecked = false;
                    if (i == position) {
                        response_grid_loadtype.isChecked = true;
                    }
                }
                //更改上方区域中的内容
                tv_talk_pinggu.setText(mResponse_grid_loadtypeList.get(position).title);
                tv_talk_pinggu.setTextColor(Color.parseColor("#0AA8DF"));
                mWangDianMsgAdapter.notifyDataSetChanged();
                talkPopwindow.dismiss();

            }
        });
        return msgView;
    }

    private void listViewAnimation(ListView listview) {
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(listview, "translationY", -100.0f, 0);
        AnimatorSet set = new AnimatorSet();
        set.play(animator1);
        set.setDuration(300);
        set.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
